package com.example.library.service;

import com.example.library.entity.Admin;
import com.example.library.entity.User;
import com.example.library.mapper.AdminMapper;
import com.example.library.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailService implements UserDetailsService {
    Logger logger = LoggerFactory.getLogger(UserDetailService.class);

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        logger.info("查询用户名：" + name);

        // 查询管理员
        Admin admin = adminMapper.selectByAdminName(name);
        if (admin != null) {
            logger.info("管理员信息：" + admin);
            return org.springframework.security.core.userdetails.User
                    .withUsername(admin.getName())
                    .password(admin.getPassword())
                    .authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))
                    .build();
        }

        // 查询普通用户
        User normalUser = userMapper.findByUserName(name);
        if (normalUser != null) {
            logger.info("普通用户信息：" + normalUser);
            return org.springframework.security.core.userdetails.User
                    .withUsername(normalUser.getName())
                    .password(normalUser.getPassword())
                    .authorities(new SimpleGrantedAuthority("ROLE_USER"))
                    .build();
        }

        throw new UsernameNotFoundException("用户不存在: " + name);
    }
}